/*
点灯
*/
#define __AVR_AVR64DD32__
#include <avr/io.h>
#include <Arduino.h>
#include <math.h>
#include <Comparator.h>

#define LED_BUILTIN PIN_PF5
#define TEMP_PIN    PIN_PD6
#define PWM_PIN     PIN_PD1
float temp;
volatile bool warning_enable =0;
unsigned int DutyCycle =0;
volatile bool warning_flag = true;

void waringFunc(void)
{
    warning_enable =1;
}
void pwm_set(void)
{
    DutyCycle=0;
    takeOverTCA0();
    PORTMUX.TCAROUTEA   = (PORTMUX.TCAROUTEA & ~(PORTMUX_TCA0_gm)) | PORTMUX_TCA0_PORTD_gc; // Set mux to PORTD
    TCA0.SINGLE.CTRLB   = (TCA_SINGLE_CMP1EN_bm | TCA_SINGLE_WGMODE_DSBOTTOM_gc); // Dual slope PWM mode OVF interrupt at BOTTOM, PWM on WO1.
    TCA0.SINGLE.PER     = 0xFFFF;               // Count all the way up to 0xFFFF.
    //                                             At 20MHz, this gives ~152Hz PWM with no prescaling.
    TCA0.SINGLE.CMP1    = DutyCycle;            // 0 - 65535
    TCA0.SINGLE.INTCTRL = TCA_SINGLE_OVF_bm;    // enable overflow interrupt
    TCA0.SINGLE.CTRLA   = TCA_SINGLE_ENABLE_bm; // enable the timer with no prescaler
}
ISR(TCA0_OVF_vect) {    // on overflow, we will increment TCA0.CMP0, this will happen after every full cycle - a little over 7 minutes.
  TCA0.SINGLE.CMP1      = DutyCycle++; // Because we are in Dual Slope Bottom mode, OVF fires at BOTTOM, at end, not TOP, in middle of the pulse.
  TCA0.SINGLE.INTFLAGS  = TCA_SINGLE_OVF_bm; // Always remember to clear the interrupt flags, otherwise the interrupt will fire continually!
}
void Compare_set(uint8_t value)
{
    Comparator.input_p = comparator::in_p::inputP_t::pd6;
    Comparator.input_n = comparator::in_n::inputN_t::dacref;
    Comparator.dacref = value;

    Comparator.reference = comparator::ref::vref_1v024; // Set the DACREF voltage to 1.024
    Comparator.hysteresis = comparator::hyst::disable;  // Use a 50mV hysteresis
    Comparator.output = comparator::out::disable;     // Use interrupt trigger instead of output pin
    Comparator.init();
    Comparator.attachInterrupt(waringFunc,RISING);
    Comparator.start();
}
void setup() {
  pinMode(LED_BUILTIN, OUTPUT);
  Serial1.begin(115200);
  delay(1000);
  Compare_set(220);
  pinMode(PWM_PIN,OUTPUT);
}

void loop() {
temp = (float)analogRead(TEMP_PIN)*0.00322265625f ;
  if((temp<0.75)&&(warning_flag)&&(temp>0))
  {
    warning_flag=false;
    takeOverTCA0();
    Comparator.start();
    Serial1.println("stop warning!");
  }
  
  if(warning_enable)
  {
    warning_enable =0;
    Comparator.start(false);
    warning_flag = true;
    Serial1.println("temp high! start waring");
    Serial1.println(temp);
    Serial1.println(temp*100-50);
    pwm_set();
    
  }
}
